<?php
require('config.php');
require('functions.php');
require('facebooksdk/src/facebook.php');
requireAuth();
$facebook = new Facebook($fbconfig);
$user_id = $facebook->getUser();
if($user_id) {
	try {
		$token = isset($_SESSION['cs_tmp_token']) ? $_SESSION['cs_tmp_token'] : $facebook->getAccessToken();
		// get long live access token
		$longLiveToken = renewFbToken($token);
		if(isset($longLiveToken['access_token'])){
			// update user token
			$_SESSION['cs_access_token'] = $longLiveToken['access_token'];
			// get long-live page access token
			$facebook->setAccessToken($longLiveToken['access_token']);
			$request = $facebook->api(_FB_API_VERSION . '/' . $user_id . '/accounts');
			$requestGroup = $facebook->api(_FB_API_VERSION . '/' . $user_id . '/groups?limit=5000&fields=id,name,bookmark_order');
			if(!empty($request['data'])){
				foreach($request['data'] as $page){
					$sql = "INSERT INTO pages(user_id, fb_user_id, fb_page_id, page_name, page_token, page_data, auth_date) VALUES (
						$userId,
						'$user_id',
						'".$page['id']."',
						'".$page['name']."',
						AES_ENCRYPT('".$page['access_token']."', '". SALT_KEY ."'),
						'".json_encode($page)."',
						NOW()
						) ON DUPLICATE KEY UPDATE page_name='".$page['name']."', page_token=AES_ENCRYPT('".$page['access_token']."', '". SALT_KEY ."'),page_data='".json_encode($page)."', auth_date=NOW()";
					mysql_query($sql);
				}
				// update user's data
				$userInfo = $facebook->api(_FB_API_VERSION . '/me');
				$_SESSION['cs_user_authorized'] = 'YES';
				$userFbData = json_encode($userInfo);
				mysql_query("UPDATE users SET user_fb_id='" . $user_id . "', user_fb_data='" . addslashes($userFbData) . "', user_authorized='YES' WHERE user_id=" . $userId);

				$pageInfo = getPagesByUser($userId);
				$_SESSION['cs_user_pages'] = $pageInfo;
				$_SESSION['cs_user_fb_data'] = json_decode($userFbData, true);
			}
			if(!empty($requestGroup['data'])){
				foreach($requestGroup['data'] as $group){
					$sql = "INSERT INTO groups(user_id, fb_user_id, fb_group_id, group_name, group_data, group_bookmark_order, auth_date) VALUES (
						$userId,
						'$user_id',
						'".$group['id']."',
						'".$group['name']."',
						'".json_encode($group)."',
						'".$group['bookmark_order']."',
						NOW()
						) ON DUPLICATE KEY UPDATE group_name='".$group['name']."', group_bookmark_order='".$group['bookmark_order']."', group_data='".json_encode($group)."', auth_date=NOW()";
					mysql_query($sql);
				}
				$groupInfo = getGroupsByUser($userId);
				$_SESSION['cs_user_groups'] = $groupInfo;
			}
			makeRedirect(route("settings"));
		}
		else{
			echo 'Could not change to long-live token';
		}
	} catch(FacebookApiException $e) {
		// If the user is logged out, you can have a 
		// user ID even though the access token is invalid.
		// In this case, we'll get an exception, so we'll
		// just ask the user to login again here.
		$login_url = $facebook->getLoginUrl($fbperm); 
		echo 'Please <a href="' . $login_url . '">login.</a>';
		echo ($e->getType());
		echo ($e->getMessage());
	}   
} else {
	// No user, so print a link for the user to login
	// To post to a user's wall, we need publish_stream permission
	// We'll use the current URL as the redirect_uri, so we don't
	// need to specify it here.
	$login_url = $facebook->getLoginUrl($fbperm);
	makeRedirect($login_url);
} 
?>